#!/bin/sh
## Adapted from https://gist.github.com/nl5887/a511f172d3fb3cd0e42d.
## Original author:
##   Remco Verhoef <remco@dutchcoders.io>

curl --version 2>&1 > /dev/null
if [ $? -ne 0 ]; then
	echo "Could not find curl."
	exit 1
fi

if [ $# -eq 0 ]; then
	cat<<EOF
No arguments specified.

Usage: transfer FILES
       cat FILE | transfer FOO
EOF
	exit 1
fi

# Get temporarily filename, output is written to this file so progress can be showed.
tmpfile=$( mktemp -t transferXXX )

# upload stdin or file
if tty -s; then
	for file; do
		basefile=$(basename "$file" | sed -e 's/[^a-zA-Z0-9._-]/-/g')

		if [ ! -e "$file" ]; then
			echo "File $file doesn't exists."
			exit 1
		fi

		if [ -d "$file" ]; then
			# zip directory and transfer
			zipfile=$( mktemp -t transferXXX.zip )
			cd $(dirname $file) && zip -r -q - $(basename $file) > $zipfile
			curl --progress-bar --upload-file "$zipfile" "https://transfer.sh/$basefile.zip" > $tmpfile
			rm -f $zipfile
		else
			# transfer file
			curl --progress-bar --upload-file "$file" "https://transfer.sh/$basefile" > $tmpfile
			# cat output link
			out="$out
$(cat $tmpfile)"
		fi
	done
	echo "$out"
else
	# transfer pipe
	curl --progress-bar --upload-file "-" "https://transfer.sh/$file" >> $tmpfile
	# cat output link
	cat $tmpfile
	echo
fi

# cleanup
rm -f $tmpfile
